﻿module Billing

open IntelliFactory.WebSharper
open IntelliFactory.WebSharper.Html
open IntelliFactory.WebSharper.JQuery
open IntelliFactory.WebSharper.JQuery.Mobile
open System

type BillingInfo = {Year:int; Month:string; BillDate:DateTime; Amount:float}

[<Rpc>]
let getBilling() =
    let rnd = System.Random()
    [for y in 2012..-1..1998 do
        for m in 12..-1..1 do
            let billdate = DateTime(y,m,1)
            yield
                {
                    Year = y
                    Month = billdate.ToString("MMM")
                    BillDate = billdate
                    Amount = rnd.Next(100,200) |> float
                }]

[<Rpc>]
let getBillingAsyc() =
    async {
        do! Async.Sleep 2000 // a two second delay to emulate likely actual-use scenario
        return getBilling() 
    }

[<JavaScript>]
let BillingsPageContent() = JQuery.Of("#billing").Children(":jqmData(role=content)")

[<JavaScript>]
let LoadBillingInfo() =
    async {
        let! bills = getBillingAsyc()
        let _,listItems = ((0,[]), bills) ||> List.fold (fun (prevYear,acc) bill ->

            let changed = prevYear <> bill.Year
            let nextYear = if changed then bill.Year else prevYear

            let item = 
                if changed then
                    LI [HTML5.Attr.Data "role" "list-divider"] -< [Text (bill.Year.ToString())]
                else
                    LI []  -< [
                        Div [Attr.Class "ui-grid-a"] -< [
                                Div[Attr.Class "ui-block-a"] -<  [Text bill.Month]
                                Div[Attr.Class "ui-block-b"] -<  [Text(" $"); Text(bill.Amount.ToString())]
                            ]                
                       ]

            nextYear,item::acc
            )
        let children = UL[HTML5.Attr.Data "role" "listview"; Id "billingHistory"] -< (listItems |> List.rev)
//            Div[] -< [
//                
//            ]

        let jq =BillingsPageContent().Html("")
        jq.Get(0).InsertBefore(children.Dom,null) |> ignore
        jq.Trigger("create") |> ignore
//        BillingsPageContent().Html(children.Html).Trigger("create") |> ignore
    }

[<JavaScript>]
let BillingPage () = 
    
    let header =
        Div [HTML5.Attr.Data "role" "header"; HTML5.Attr.Data "theme" "b"] -< [

                SiteCommon.homeButton()

                H1 [Text "Billing History"]
            ]

    let content = Div [HTML5.Attr.Data "role" "content"] 

    let page = 
        Div [Id "billing"; HTML5.Attr.Data "role" "page"] -< [
            header
            content
            SiteCommon.footer MainPages.Billing
            ]
        |>! OnBeforeShow (fun _ -> BillingsPageContent() |> ShowBusy)
        |>! OnShow (fun p -> LoadBillingInfo() |> Async.Start)
    page
